package com.tianyuan.lims.utils;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;

import java.io.File;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ActiveRecordScanner {

    public static String convertToTableName(String fullyQualifiedClassName) {
        // 移除包名部分
        int lastIndex = fullyQualifiedClassName.lastIndexOf('.');
        if (lastIndex != -1) {
            fullyQualifiedClassName = fullyQualifiedClassName.substring(lastIndex + 1);
        }

        // 移除Entity后缀（如果有的话）
        if (fullyQualifiedClassName.endsWith("Entity")) {
            fullyQualifiedClassName = fullyQualifiedClassName.substring(0, fullyQualifiedClassName.length() - "Entity".length());
        }

        // 将驼峰命名转换为下划线命名
        StringBuilder tableName = new StringBuilder();
        for (int i = 0; i < fullyQualifiedClassName.length(); i++) {
            char c = fullyQualifiedClassName.charAt(i);
            if (Character.isUpperCase(c) && i > 0) {
                tableName.append('_');
            }
            tableName.append(Character.toLowerCase(c));
        }

        return tableName.toString();
    }


    public static void scanAndRegister(ActiveRecordPlugin arp, String packageName) {
        try {

            // 将包名转换为路径
            String path = packageName.replace('.', '/');
            // 获取类加载器
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            // 获取包对应的 URL
            Enumeration<URL> resources = classLoader.getResources(path);
            List<File> dirs = new ArrayList<>();

            // 检查是否有资源（即目录）
            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                dirs.add(new File(resource.getFile()));
            }
            // 遍历目录，加载类
            for (File directory : dirs) {
                    File[] files = directory.listFiles();
                    if (files != null) {
                        for (File file : files) {
                            if (file.isFile() && file.getName().endsWith(".class")) {
                                // 移除 .class 后缀并转换为类名
                                String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                                try {
                                    Class<?> clazz = Class.forName(className, false, classLoader);
                                    if (!Modifier.isAbstract(clazz.getModifiers()) && Model.class.isAssignableFrom(clazz)) {
                                        String tableName = convertToTableName(clazz.getName()); // 或者你可以从其他地方获取表名
                                        String primaryKey = "id"; // 假设主键总是"id"，或者你可以从其他地方获取
                                        arp.addMapping(tableName, primaryKey, (Class<? extends Model<?>>) clazz);
                                    }
                                } catch (ClassNotFoundException e) {
                                    // 忽略找不到的类（理论上不应该发生，因为我们是从目录中获取的类名）
                                    e.printStackTrace();
                                }
                            }
                        }
                        int a = 0 ;
                    }
                }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
